package controllers;

import helpers.DateHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import debugs.CheckSpeedDebug;

import services.GetInfoDomain;
import systems.CurrentProcess;
import systems.RecentlyDomain;
import systems.RecentlyUpdate;

import models.CheckSpeedModel;
import models.DirectoryModel;
import models.DomainAnalyticModel;
import models.GoogleAdsenceModel;
import models.GoogleAnalyticModel;
import models.InLinkModel;
import models.IpAddressModel;
import models.DomainModel;
import models.OwnerDomainModel;

import entities.CheckSpeed;
import entities.Domain;
import entities.DomainAnalytic;
import entities.GoogleAdsense;
import entities.GoogleAnalytic;
import entities.InLink;
import entities.IpAddress;
import entities.OwnerDomain;
import entities.User;

public class DomainInfoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (name == null || name.isEmpty() || !UrlHelper.checkDomain(name)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (!name.equalsIgnoreCase(UrlHelper.getMainDomain(name))) {
			response.sendRedirect("/info/" + UrlHelper.getMainDomain(name));
			return ;
		}
		
		DomainModel domainModel = DomainModel.getInstance();
		Domain domain = domainModel.get(name);
		
		if (domain == null) {
			/*response.sendRedirect("/process/" + name);
			return;*/
			
			//Get data
			domain = new Domain();
			domain.setProcessing(true);
			domain.setDomain(name);
			
			
			GetInfoDomain getInfoDomain = new GetInfoDomain(domain);
			getInfoDomain.getSiteInfo();
			
			domain = getInfoDomain.getDomain();
			TreeMap check = getInfoDomain.getCheck();
			
			if (!domain.isExists()) {
				response.sendRedirect("/msg/page-not-found");
				return;
			}
			
			domainModel.insert(domain);
			
			//Get more info
			if (domain.isExists()) {
				getInfoDomain.getStep1();
				
				domain.setProcessing(false);
				domainModel.insert(domain);
				
				//Update googleAnalytic model
				if (!domain.getGoogleAnalyticId().isEmpty()) {
					GoogleAnalyticModel googleAnalyticModel = GoogleAnalyticModel.getInstance();
					googleAnalyticModel.insert(domain.getGoogleAnalyticId(), domain.getDomain());
				}
				
				//Update googleAdsense model
				if (!domain.getGoogleAdsenseId().isEmpty()) {
					GoogleAdsenceModel googleAdsenseModel = GoogleAdsenceModel.getInstance();
					googleAdsenseModel.insert(domain.getGoogleAdsenseId(), domain.getDomain());
				}
				
				//Update IpAddress Model
				if (!domain.getIpAddress().isEmpty()) {
					IpAddressModel ipAddressModel = IpAddressModel.getInstance();
					ipAddressModel.insert(domain.getIpAddress(), domain.getDomain());
				}
				
				//Update inlink
				/*if (domain.getOutlink().size() > 0) {
					InLinkModel inlinkModel = InLinkModel.getInstance();
					inlinkModel.insert(domain.getDomain(), domain.getOutlink());
				}*/
				
				CurrentProcess.remove(name);
				RecentlyUpdate.insert(name);
				
				//Update directory
				DirectoryModel directoryModel = DirectoryModel.getInstance();
				directoryModel.insert(domain.getDomain());
			}
			
			//Get check speed
			if (domain.isExists()) {
				Queue queue = QueueFactory.getQueue("checkspeed");
				queue.add(TaskOptions.Builder.withUrl("/queue-process-get-check-speed/" + name).method(Method.GET));
			}
			
		}
		
		if (!domain.isExists()) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (domain.getStatus() == -1) {
			response.sendRedirect("/msg/blacklist");
			return;
		}
		
		OwnerDomainModel ownerData = OwnerDomainModel.getInstance();
		OwnerDomain ownerDomain = ownerData.getByDomain(name);
		if (ownerDomain != null && ownerDomain.getActive() == 0) {
			User user = (User) request.getAttribute("user_logged_in");
			if (user == null || user.getUsername().isEmpty() || !ownerDomain.getUsername().equalsIgnoreCase(user.getUsername())) {
				response.sendRedirect("/msg/page-not-found");
				return;
			}
		}
		
		//Get google analytic
		GoogleAnalyticModel googleAnalyticData = GoogleAnalyticModel.getInstance();
		GoogleAnalytic googleAnalytic = googleAnalyticData.get(domain.getGoogleAnalyticId());
		
		//Get google adsence
		GoogleAdsenceModel googleAdsenceData = GoogleAdsenceModel.getInstance();
		GoogleAdsense googleAdsense = googleAdsenceData.get(domain.getGoogleAdsenseId());
		
		//Get inlink
		InLinkModel oData = InLinkModel.getInstance();
		InLink inlink = oData.get(domain.getDomain());
		
		//Get domain analytic
		DomainAnalyticModel domainAnalyticData = DomainAnalyticModel.getInstance();
		DomainAnalytic domainAnalytic = domainAnalyticData.get(name);
		
		//Get same domain ip address
		IpAddressModel ipAddressModel = IpAddressModel.getInstance();
		IpAddress ipAddress = null;
		if (!domain.getIpAddress().isEmpty()) {
			ipAddress = ipAddressModel.get(domain.getIpAddress());
		}
		
		//Get checkspeed domain
		CheckSpeedModel checkSpeedModel = CheckSpeedModel.getInstance();
		CheckSpeed checkSpeed = checkSpeedModel.get(domain.getDomain());
		
		if (checkSpeed != null && !checkSpeed.getId().isEmpty() && checkSpeed.isProcessing() && !DateHelper.checkGreaterNow(checkSpeed.getUpdate(), 2)) {
			Queue queue = QueueFactory.getQueue("checkspeed");
			queue.add(TaskOptions.Builder.withUrl("/queue-process-get-check-speed/" + name).method(Method.GET));
		}
		
		//Set into recentSiteUpdate
		RecentlyDomain.insert(name);
		
		//Cache header
		response.addHeader("Cache-Control", "public");
		response.addHeader("Cache-Control", "max-age=" + 60000);
		
		request.setAttribute("domain", domain);
		request.setAttribute("domainAnalytic", domainAnalytic);
		request.setAttribute("googleAnalytic", googleAnalytic);
		request.setAttribute("googleAdsense", googleAdsense);
		request.setAttribute("inlink", inlink);
		request.setAttribute("ipAddress", ipAddress);
		request.setAttribute("checkSpeed", checkSpeed);
		try {
			request.getRequestDispatcher("/pages/info.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
}
